package com.shievy.anweb.base.helper;

import android.util.Log;

import com.shievy.anweb.base.uitl.LogUtil;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Iterator;
import java.util.ServiceLoader;

/**
 * 适用于 AutoService
 */
public final class LoaderServiceHelper {
    /**
     * 用于缓存已创建的服务对象
     */
    private static HashMap<Class<?>, WeakReference<Object>> serviceHashMap = null;
    /**
     * 同于同步锁操作
     */
    private static Object object = null;


    /**
     * 加载并缓存 只适用于单个 @AutoService
     */
    public static <S> S load(Class<S> cls) {
        try {
            if (object == null) {
                object = new Object();
            }
            synchronized (object) {
                if (serviceHashMap == null) {
                    serviceHashMap = new HashMap<>();
                }
                if (serviceHashMap.containsKey(cls) && serviceHashMap.get(cls) != null && serviceHashMap.get(cls).get() != null) {
                    LogUtil.INSTANCE.e("LoaderServiceHelper ", serviceHashMap.get(cls).get());
                    return (S) serviceHashMap.get(cls).get();
                } else {
                    WeakReference<Object> loaderWeakReference = new WeakReference<>(ServiceLoader.load(cls).iterator().next());
                    serviceHashMap.put(cls, loaderWeakReference);
                    return (S) loaderWeakReference.get();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



}
